import {AfterViewInit, Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core';
import {Message} from '../../../../../../ng-tools/src/message/message';
import {AlertOptions, DynamicComponent, DynamicComponentEvent} from '../../../../../../ng-tools';
import {Subscription} from 'rxjs';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../../services/api/ticket.service';
import {HttpParams} from '@angular/common/http';

@Component({
  selector: 'user-bank',
  templateUrl: './user-bank.component.html',
  styleUrls: ['./user-bank.component.scss']
})
export class UserBankComponent implements OnInit, AfterViewInit, OnDestroy, Message, DynamicComponent  {
    context: any;
    bankInfo;
    dynamic: true;
    events: DynamicComponentEvent;
    subscriptions: Subscription;
    alertOptions: AlertOptions = {
        data: null,
        position: 'center'
    };
    @Output() success = new EventEmitter();
    bankForm: FormGroup;
    set data(value: any) {
        this.bankInfo = value;
    }
  constructor(private formBuilder: FormBuilder,
              private ticketService: TicketService) {
      this.bankForm = this.formBuilder.group({
          id: ['', Validators.required],
          bankName: ['', Validators.required],
          userName: ['', Validators.required],
          number: ['', Validators.required],
          subAddr: ['', Validators.required],
      });
  }

  ngOnInit() {
      this.bankForm.patchValue(this.bankInfo);
  }
    trigger(eventName: string, ...args) {
        this[eventName].emit(...args);
        if (eventName in this.events) {
            this.events[eventName](...args);
        }
    }
    save() {
        if (this.bankForm.valid) {
            this.ticketService.post(this.ticketService.urls.saveAccountInfo, this.bankForm.value, {
              observe: 'response',
              params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
                this.trigger('success');
            });
        }
    }
    ngAfterViewInit(): void {
    }

    ngOnDestroy(): void {
    }

}
